<template>
    <div class="monitor">
        <!-- 左边分级框 -->
        <div class="tree">
          <!-- 车辆车队状态选择框 -->
          <el-tabs type="border-card">
            <!-- 全部 -->
            <el-tab-pane label="全部">
              <!-- 检索框 -->
              <el-input
                placeholder="输入关键字进行过滤"
                v-model="totalText">
              </el-input>
              <!-- 树状结构车组 -->
              <el-tree
                :data="totalData"
                ref="totalTree"
                show-checkbox
                @node-contextmenu="rightClick"
                node-key="value"
                @node-click="getTotalDetail"
                :filter-node-method="filterNode"
                default-expand-all>
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                      <span>
                          <i :class="data.icon"></i>{{ node.label }}
                      </span>              
                  </span>
              </el-tree>
            </el-tab-pane>
            <!-- 在线 -->
            <el-tab-pane label="在线">
              <!-- 检索框 -->
              <el-input
                placeholder="输入关键字进行过滤"
                v-model="onlineText">
              </el-input>
              <!-- 树状结构车组 -->
              <el-tree
                :data="onlineData"
                ref="onlineTree"
                show-checkbox
                node-key="value"
                @node-click="getOnlineDetail"
                :filter-node-method="filterNode"
                default-expand-all>
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                      <span>
                          <i :class="data.icon"></i>{{ node.label }}
                      </span>              
                  </span>
              </el-tree>
            </el-tab-pane>
            <el-tab-pane label="离线">
              <!-- 检索框 -->
              <el-input
                placeholder="输入关键字进行过滤"
                v-model="offlineText">
              </el-input>
              <!-- 树状结构车组 -->
              <el-tree
                :data="offlineData"
                ref="offlineTree"
                show-checkbox
                node-key="value"
                @node-click="getOfflineDetail"
                :filter-node-method="filterNode"
                default-expand-all>
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                      <span>
                          <i :class="data.icon"></i>{{ node.label }}
                      </span>              
                  </span>
              </el-tree>
            </el-tab-pane>
          </el-tabs>
        </div>
        
        <!-- 百度地图及监控框 -->
        <div class="monitor-type">
            <el-tabs v-model="activeName1" @tab-click="handleClick1">
              <!-- 综合监控 -->
                <el-tab-pane label="综合监控" name="first">
                    <div id="map"></div>
                    <div id="map-data">
                        <el-tabs v-model="activeName2" type="card" @tab-click="handleClick2">
                          <!-- 实时数据 -->
                            <el-tab-pane label="实时数据" name="first">
                              <el-table
                                  :data="realTimeData"
                                  border
                                  :row-style="iRowStyle"
                                  :cell-style="iCellStyle"
                                  :header-row-style="iHeaderRowStyle"
                                  :header-cell-style="iHeaderCellStyle"
                                  style="width: 100%" 
                                  height="200px">
                                  <el-table-column
                                    prop="brand"
                                    label="车牌号"
                                    :show-overflow-tooltip = "true"
                                    width="100">
                                  </el-table-column>
                                  <el-table-column
                                    prop="time"
                                    label="位置时间"
                                    :show-overflow-tooltip = "true"
                                    width="180">
                                  </el-table-column>
                                  <el-table-column
                                    prop="position"
                                    label="位置"
                                    :show-overflow-tooltip = "true"
                                    width="180">
                                  </el-table-column>
                                  <el-table-column
                                    prop="speed"
                                    label="速度"
                                    :show-overflow-tooltip = "true"
                                    width="150">
                                  </el-table-column>
                                  <el-table-column
                                    prop="police"
                                    label="报警"
                                    :show-overflow-tooltip = "true"
                                    width="180">
                                  </el-table-column>
                                  <el-table-column
                                    prop="state"
                                    label="状态"
                                    :show-overflow-tooltip = "true"
                                    width="50">
                                  </el-table-column>
                                  <el-table-column
                                    prop="mileage"
                                    label="里程"
                                    :show-overflow-tooltip = "true"
                                    width="100">
                                  </el-table-column>
                                  <el-table-column
                                    prop="other"
                                    label="其它信息"
                                    :show-overflow-tooltip = "true"
                                    width="180">
                                  </el-table-column>
                                  <el-table-column
                                    prop="driver"
                                    label="司机信息"
                                    :show-overflow-tooltip = "true"
                                    width="180">
                                  </el-table-column>
                                  <el-table-column
                                    prop="login"
                                    label="司机刷卡时间"
                                    :show-overflow-tooltip = "true"
                                    width="180">
                                  </el-table-column>
                                  <el-table-column
                                    prop="operate"
                                    label="司机运营时间"
                                    :show-overflow-tooltip = "true"
                                    width="180">
                                  </el-table-column>
                                </el-table>
                            </el-tab-pane>
                            <!-- 报警数据 -->
                            <el-tab-pane label="报警数据" name="second">
                              <el-table
                                :data="alertData"
                                border
                                :row-style="iRowStyle"
                                :cell-style="iCellStyle"
                                :header-row-style="iHeaderRowStyle"
                                :header-cell-style="iHeaderCellStyle"
                                style="width: 100%" 
                                height="200px">
                                <el-table-column
                                  prop="operation"
                                  label="操作"
                                  :show-overflow-tooltip = "true"
                                  width="80">
                                </el-table-column>
                                <el-table-column
                                  prop="company"
                                  label="所属公司"
                                  :show-overflow-tooltip = "true"
                                  width="200">
                                </el-table-column>
                                <el-table-column
                                  prop="brand"
                                  label="车牌号"
                                  :show-overflow-tooltip = "true"
                                  width="100">
                                </el-table-column>
                                <el-table-column
                                  prop="num"
                                  label="报警数目"
                                  :show-overflow-tooltip = "true"
                                  width="80">
                                </el-table-column>
                                <el-table-column
                                  prop="newt"
                                  label="最新报警"
                                  :show-overflow-tooltip = "true"
                                  width="180">
                                </el-table-column>
                                <el-table-column
                                  prop="startt"
                                  label="开始时间"
                                  :show-overflow-tooltip = "true"
                                  width="160">
                                </el-table-column>
                                <el-table-column
                                  prop="endt"
                                  label="结束时间"
                                  :show-overflow-tooltip = "true"
                                  width="160">
                                </el-table-column>
                                <el-table-column
                                  prop="message"
                                  label="报警信息"
                                  :show-overflow-tooltip = "true"
                                  width="100">
                                </el-table-column>
                                <el-table-column
                                  prop="startp"
                                  label="开始位置"
                                  :show-overflow-tooltip = "true"
                                  width="180">
                                </el-table-column>
                                <el-table-column
                                  prop="endp"
                                  label="结束位置"
                                  :show-overflow-tooltip = "true"
                                  width="180">
                                </el-table-column>
                              </el-table>
                            </el-tab-pane>
                        </el-tabs>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="实时视频" name="second">实时视频</el-tab-pane>
            </el-tabs>
        </div>

        <!-- 下发文本指令 -->
        <el-dialog
          title="下发文本指令"
          :visible.sync="dialogOrder"
          width="500px"
          :before-close="handleClose"
        >
          <!-- 下发类型 -->
          <el-form ref="form" :model="form" label-width="80px">
            <!-- 选中车辆 -->
            <el-form-item label="车辆">
              <el-input v-model="form.car" placeholder="请选择" readonly @click.native="dialogCarVisible=true"></el-input>
            </el-form-item>

            <!-- 下发文本类型 -->
            <el-form-item label="标志">
              <el-checkbox-group v-model="form.type">
                <el-checkbox label="紧急" name="type"></el-checkbox>
                <el-checkbox label="终端显示器显示" name="type"></el-checkbox>
                <el-checkbox label="终端TTS播读" name="type"></el-checkbox>
                <el-checkbox label="广告屏显示" name="type"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <!-- 指令内容 -->
            <el-form-item label="文本信息">
              <el-input type="textarea" v-model="form.txt"></el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="issueOrder">下发指令</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>

        <!-- 选择车辆 -->
      <el-dialog title="选择车辆" :visible.sync="dialogCarVisible" width="500px">
        <car-list @option-car="optionCar" :isDialog="true"></car-list>
      </el-dialog>
    </div>
</template>

<script>
import BMap from "BMap";
import monitorApi from "@/api/monitor"
import CarList from '@/views/carList'

  export default {
    name: 'Map',
    components: {CarList},

    data() {
      return {
        menuVisible: false,
        totalText: '',
        onlineText: '',
        offlineText: '',
        activeName1: 'first',
        activeName2: 'first',
        totalData: [],
        onlineData: [],
        offlineData: [],
        dialogOrder: false, //文本指令
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        realTimeData: [],
        alertData: [],
        longitude: 116.404, //经度
        latitude: 39.915, //纬度
        timeCar: '粤ABC660', //当前车辆
        searchT: '2020-06-30:12:00:00', //选中时间
        speed: '0公里/时',
        position: '广东省广州市黄埔区南翔支路1号瑞粤汽车电子创新园',
        speedD: '0公里/时',
        mileage: '100000公里',
        state: '模拟量：AD0:bit(1),AD1:bit(17,18),(在线)ACC关闭，停车(2分53秒),运营状态,经纬度未加密,车门解锁,空载,门1关(前门),门2关（中门),门3关(后门),门4关(驾驶席门),门5关(自定义),未使用位置卫星进行定位，未使用北斗卫星进行定位,未使用GLONASS卫星进行定位,未使用Galileo卫星进行定位,卫星数:15',
        timer: '',
        // 文本信息弹框
        form: {
          car: '',
          type: [],
          txt: ''
        },
        dialogCarVisible: false,
      }
    },

    watch: {
      totalText(val) {
        this.$refs.totalTree.filter(val);
      },
      onlineText(val) {
        this.$refs.onlineTree.filter(val)
      }
    },

    mounted(){
        this.createMap(),
        this.getTotalState(),
        this.getOnlineState(),
        this.getOfflineState(),
        this.getAlertMessage()
    },

    methods: {
      // 右击事件
      rightClick(event, object, value, element){
        // this.menuVisible = !this.menuVisible
        // let menu = document.querySelector("#menu")
        // menu.style.left = event.clientX + 20 + "px";
        // menu.style.top = event.clientY -60 + "px";

        console.log(object.label)
        this.form.car = object.label
        this.dialogOrder = true

        console.log("右键被点击的event:", event)
        console.log("右键被点击的object:", object)
        console.log("右键被点击的value:", value)
        console.log("右键被点击的element:", element)
      },

      // 获取所有车组车辆状态
      getTotalState() {
        const token = localStorage.getItem('seeto-token')
        monitorApi.totalData(token).then(response => {
          const resp = response.data
          if(resp.flag){
            var respD = response.data.data.data
            this.totalData = respD
          }else{
            this.$message({
              message: resp.message,
              type: 'warning'
            })
          }
        })
      },

      // 获取在线车组车辆状态
      getOnlineState() {
        const token = localStorage.getItem('seeto-token')
        monitorApi.onlineData(token).then(response => {
          const resp = response.data
          if(resp.flag){
            var respD = response.data.data.data
            this.onlineData = respD
          }else{
            this.$message({
              message: resp.message,
              type: 'warning'
            })
          }
        })
      },

      // 获取离线车组车辆状态
      getOfflineState() {
        const token = localStorage.getItem('seeto-token')
        monitorApi.offlineData(token).then(response => {
          const resp = response.data
          if(resp.flag){
            var respD = response.data.data.data
            this.offlineData = respD
          }else{
            this.$message({
              message: resp.message,
              type: 'warning'
            })
          }
        })
      },

      // 点击获取车辆详情
      getTotalDetail () {
        var aKey = this.getCheckedKeys(this.totalData, this.$refs.totalTree.getCheckedKeys(), 'value')
        console.log(aKey)
        this.getRealTimeData(aKey)
        if(aKey == ''){
          console.log('123')
          clearInterval(this.timer)
          this.createMap()
        }else{
          // 第一次获取定位
          monitorApi.carDetail(aKey.id).then(response => {
              const resp = response.data
              if(resp.flag){
                const respD = resp.data
                this.longitude = respD.longitude
                this.latitude = respD.latitude
                this.timeCar = respD.title
                this.searchT = respD.time
                this.speed = respD.speed
                this.position = respD.position
                this.speedD = respD.speedD
                this.mileage = respD.mileage
                this.state = respD.state
                this.changeMap()
              }else{
                this.$message({
                  message: this.message,
                  type: 'warning'
                })
              }
            })
            if(this.tiemr != ''){
              clearInterval(this.timer)
            }
          // 每30秒获取一次数据
          const me = this
          this.timer = window.setInterval(() => {
            setTimeout(
              function(){
                monitorApi.carDetail(aKey.id).then(response => {
                  const resp = response.data
                  if(resp.flag){
                    const respD = resp.data
                    me.longitude = respD.longitude
                    me.latitude = respD.latitude
                    me.timeCar = respD.title
                    me.searchT = respD.time
                    me.speed = respD.speed
                    me.position = respD.position
                    me.speedD = respD.speedD
                    me.mileage = respD.mileage
                    me.state = respD.state
                    me.changeMap()
                  }else{
                    this.$message({
                      message: this.message,
                      type: 'warning'
                    })
                  }
                }, 0)
              }
            )
          }, 30000)
        }
      },
      getOnlineDetail (){
        var aKey = this.getCheckedKeys(this.onlineData, this.$refs.onlineTree.getCheckedKeys(), 'value')
        console.log(aKey)
        this.getRealTimeData(aKey)
        if(aKey == ''){
          console.log('123')
          clearInterval(this.timer)
          this.createMap()
        }else{
          // 第一次获取定位
          monitorApi.carDetail(aKey.id).then(response => {
              const resp = response.data
              if(resp.flag){
                const respD = resp.data
                this.longitude = respD.longitude
                this.latitude = respD.latitude
                this.timeCar = respD.title
                this.searchT = respD.time
                this.speed = respD.speed
                this.position = respD.position
                this.speedD = respD.speedD
                this.mileage = respD.mileage
                this.state = respD.state
                this.changeMap()
              }else{
                this.$message({
                  message: this.message,
                  type: 'warning'
                })
              }
            })
            if(this.tiemr != ''){
              clearInterval(this.timer)
            }
          // 每30秒获取一次数据
          const me = this
          this.timer = window.setInterval(() => {
            setTimeout(
              function(){
                monitorApi.carDetail(aKey.id).then(response => {
                  const resp = response.data
                  if(resp.flag){
                    const respD = resp.data
                    me.longitude = respD.longitude
                    me.latitude = respD.latitude
                    me.timeCar = respD.title
                    me.searchT = respD.time
                    me.speed = respD.speed
                    me.position = respD.position
                    me.speedD = respD.speedD
                    me.mileage = respD.mileage
                    me.state = respD.state
                    me.changeMap()
                  }else{
                    this.$message({
                      message: this.message,
                      type: 'warning'
                    })
                  }
                }, 0)
              }
            )
          }, 30000)
        }
      },
      getOfflineDetail (){
        var aKey = this.getCheckedKeys(this.offlineData, this.$refs.offlineTree.getCheckedKeys(), 'value')
        console.log(aKey)
        this.getRealTimeData(aKey)
        if(aKey == ''){
          console.log('123')
          clearInterval(this.timer)
          this.createMap()
        }else{
          // 第一次获取定位
          monitorApi.carDetail(aKey.id).then(response => {
              const resp = response.data
              if(resp.flag){
                const respD = resp.data
                this.longitude = respD.longitude
                this.latitude = respD.latitude
                this.timeCar = respD.title
                this.searchT = respD.time
                this.speed = respD.speed
                this.position = respD.position
                this.speedD = respD.speedD
                this.mileage = respD.mileage
                this.state = respD.state
                this.changeMap()
              }else{
                this.$message({
                  message: this.message,
                  type: 'warning'
                })
              }
            })
            if(this.tiemr != ''){
              clearInterval(this.timer)
            }
          // 每30秒获取一次数据
          const me = this
          this.timer = window.setInterval(() => {
            setTimeout(
              function(){
                monitorApi.carDetail(aKey.id).then(response => {
                  const resp = response.data
                  if(resp.flag){
                    const respD = resp.data
                    me.longitude = respD.longitude
                    me.latitude = respD.latitude
                    me.timeCar = respD.title
                    me.searchT = respD.time
                    me.speed = respD.speed
                    me.position = respD.position
                    me.speedD = respD.speedD
                    me.mileage = respD.mileage
                    me.state = respD.state
                    me.changeMap()
                  }else{
                    this.$message({
                      message: this.message,
                      type: 'warning'
                    })
                  }
                }, 0)
              }
            )
          }, 30000)
        }
      },
      getCheckedKeys (data, keys, key) {
        var res = [];
        recursion(data, false);
        return res;
        // arr -> 树形总数据
        // keys -> getCheckedKeys获取到的选中key值
        // isChild -> 用来判断是否是子节点
        function recursion (arr, isChild) {
          var aCheck = [];
          for ( var i = 0; i < arr.length; i++ ) {
            var obj = arr[i];
            aCheck[i] = false;
            if ( obj.children ) {
              aCheck[i] = recursion(obj.children, true) ? true : aCheck[i];
              if ( aCheck[i] ) {
                res.push(obj[key]);
              }
            }
            for ( var j = 0; j < keys.length; j++ ) {
              if ( obj[key] == keys[j] ) {
                aCheck[i] = true;
                if ( res.indexOf(obj[key]) == -1 ) {
                  res.push(obj[key]);
                }
                break;
              }
            }
          }
          if ( isChild ) {
            return aCheck.indexOf(true) != -1;
          }
        }
      },

      // 获取车辆实时数据
      getRealTimeData(arr) {
        const token = localStorage.getItem('seeto-token')
        monitorApi.realTimeData(arr).then(response => {
          const resp = response.data
          if(resp.flag){
            const respD = response.data.data.data
            this.realTimeData = respD
          }else{
            this.$message({
              message: resp.message,
              type: 'warning'
            })
          }
        })
      },

      // 获取报警信息
      getAlertMessage(){
        const token = localStorage.getItem('seeto-token')
        monitorApi.alertMessage(token).then(response => {
          const resp = response.data
          if(resp.flag){
            const respD = response.data.data.data
            this.alertData = respD
          }else{
            this.$message({
              message: resp.message,
              type: 'warning'
            })
          }
        })
      },

      // 调整表格行高
      iRowStyle:function ({row, rowIndex}) {
          return 'height:35px';
      },
      iHeaderRowStyle:function ({row, rowIndex}) {
          return 'height:35px';
      },
      iCellStyle:function ({row, column, rowIndex, columnIndex}) {
          return 'padding:0px'
      },
      iHeaderCellStyle:function ({row, column, rowIndex, columnIndex}) {
          return 'padding:0px'
      },

      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },

      handleClick1(tab, event) {
        console.log(tab, event);
      },

      handleClick2(tab, event) {
          console.log(tab, event)
      },

      // 初始化地图
      createMap () {
        var map = new BMap.Map("map")
        var point = new BMap.Point(113.457261, 23.161446)
        map.centerAndZoom(point, 16)
        map.enableScrollWheelZoom(true)
        map.addControl(new BMap.NavigationControl());    
        map.addControl(new BMap.ScaleControl());    
        map.addControl(new BMap.OverviewMapControl());    
        map.addControl(new BMap.MapTypeControl({mapTypes: [BMAP_NORMAL_MAP,BMAP_SATELLITE_MAP ]}));
      },

      // 地图
      changeMap () {
        var map = new BMap.Map("map")
        var point = new BMap.Point(this.longitude, this.latitude)
        map.centerAndZoom(point, 16)
        map.enableScrollWheelZoom(true)
        map.addControl(new BMap.NavigationControl());    
        map.addControl(new BMap.ScaleControl());    
        map.addControl(new BMap.OverviewMapControl());    
        map.addControl(new BMap.MapTypeControl({mapTypes: [BMAP_NORMAL_MAP,BMAP_SATELLITE_MAP ]}));
        var marker = new BMap.Marker(point);        // 创建标注    
        map.addOverlay(marker);                     // 将标注添加到地图中 
        var opts = {    
            width : 350,     // 信息窗口宽度    
            height: 180,     // 信息窗口高度    
            title : this.timeCar  // 信息窗口标题   
        }    
        var html = '<div class="col-xs-12" style="margin-left: -40px; font-size: 2px">\n' +
				'                    <ul class="list-unstyled">\n' +
				'                      <li style="list-style-type:none;">时间：'+this.searchT+' &nbsp; 速度：'+this.speed+'</li>\n' +
				'                      <li style="list-style-type:none;">位置：'+this.position+'</li>\n' +
				'                      <li style="list-style-type:none;">行驶记录仪速度：'+this.speedD+'</li>\n' +
				'                      <li style="list-style-type:none;">里程：'+this.mileage+'</li>\n' +
				'                      <li style="list-style-type:none;">状态：'+this.state+'</li>\n' +
        '                    </ul>\n' +
				'                  </div>';
        var infoWindow = new BMap.InfoWindow(html, opts);  // 创建信息窗口对象    
        map.openInfoWindow(infoWindow, map.getCenter());      // 打开信息窗口
      },

      // 关闭对话框
      handleClose(done) {  
        done();
      },

      // 文本信息下发
      issueOrder(){
        console.log('下发文本信息')
        monitorApi.issueOrder(this.form).then(response => {
          const resp = response.data
          if(resp.flag){
            this.$message({
              message: resp.message,
              type: 'success'
            })
          }else{
            this.$message({
              message: resp.message,
              type: 'success'
            })
          }
        })
      },

      optionCar(currentRow){
        console.log('parent', currentRow)
        console.log(currentRow.carP)
        this.form.car = currentRow.carP
        this.dialogCarVisible = false
      },
    }
  };
</script>

<style>
.monitor{
    padding: 10px 5px 8px 10px;
    background-color: #eee;
}
.monitor::after{ content: ""; clear: both; display: block;}
.tree{
    width: 250px;
    overflow-y: auto;
    overflow-x: auto;
    border: 1px solid #ccc;
    background-color: #fff;
    padding: 10px;
    border-radius: 5px;
    height: 620px;
    float: left;
}
.monitor-type{
    padding: 10px 10px 0 10px;
    width: 1100px;
    margin-left: 10px;
    height: 630px;
    border: 1px solid #ccc;
    background-color: #fff;
    float: left;
}
.el-tabs__header{
  margin-bottom: 0px !important;  
}
.el-table-column{
  height: 10px;
}

#map{
    width: 100%;
    height: 350px;
}
#map-data{
    height: 240px;
}
</style>